﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Http;
using System.Threading.Tasks;

namespace Esb.Soa.Domain.ServiceHandlers
{
    /// <summary>
    /// Rest服务处理器
    /// </summary>
    public class RestServiceHandler : IServiceHandler
    {
        /// <summary>
        /// Rest请求动词
        /// </summary>
        public string HttpVerb { get; set; }

        public string ProcessCallService(string requestBody, string serviceUrl, string methodName)
        {
            Uri uri = new Uri(serviceUrl + "/" + methodName);
            string result = string.Empty;

            using (HttpClient httpClient = new HttpClient())
            {
                string contentString = requestBody;
                using (StringContent httpContent = new StringContent(contentString, Encoding.UTF8, "application/json"))
                {
                    Task<HttpResponseMessage> postTask = CreateTask(this.HttpVerb, uri, httpClient, httpContent);
                    postTask.Wait();

                    if (!postTask.Result.IsSuccessStatusCode)
                    {
                        throw new Exception(string.Format("Status Code:{0}, Reason:{1}", postTask.Result.StatusCode, postTask.Result.ReasonPhrase));
                    }
                    else
                    {
                        Task<string> readTask = postTask.Result.Content.ReadAsStringAsync();
                        readTask.Wait();
                        result = readTask.Result;
                        return result;
                    }
                }
            }
        }

        /// <summary>
        /// 根据不同的动词创建不同请求的工厂
        /// </summary>
        /// <param name="httpVerb"></param>
        /// <param name="uri"></param>
        /// <param name="httpClient"></param>
        /// <param name="httpContent"></param>
        /// <returns></returns>
        private Task<HttpResponseMessage> CreateTask(string httpVerb, Uri uri, HttpClient httpClient, HttpContent httpContent)
        {
            if (string.IsNullOrEmpty(httpVerb))
                return httpClient.PostAsync(uri, httpContent);

            switch(httpVerb.ToUpper())
            {
                case "POST":
                    return httpClient.PostAsync(uri, httpContent);
                case "PUT":
                    return httpClient.PutAsync(uri, httpContent);
                case "GET":
                    return httpClient.GetAsync(uri);
                case "DELETE":
                    return httpClient.DeleteAsync(uri);
                default:
                    return httpClient.PostAsync(uri, httpContent);
            }
        }
    }
}
